package cn.net.autocode.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class BarCodeUtils {

    public static String generateText(String barcodeText,int width,int height,int fontSize,int fontHeight){
        // 生成条形码
        Code128Writer barcodeWriter = new Code128Writer();
        BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, width, height);

        // 创建一个更大的 BufferedImage，用于容纳条形码和文字
        int totalHeight = height + fontHeight; // 假设文字高度为30像素
        BufferedImage combinedImage = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = combinedImage.createGraphics();

        // 设置背景为白色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, totalHeight);

        // 将条形码绘制到 BufferedImage 中
        BufferedImage barcodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        g2d.drawImage(barcodeImage, 0, 0, null);

        // 设置文字样式
        Font font = new Font("Arial", Font.PLAIN, fontSize);
        g2d.setFont(font);
        g2d.setColor(Color.BLACK);

        // 计算文字位置
        int textWidth = g2d.getFontMetrics().stringWidth(barcodeText);
        int x = (width - textWidth) / 2;
        int y = height + 20; // 文字位于条形码下方

        // 添加文字
        g2d.drawString(barcodeText, x, y);
        g2d.dispose();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            ImageIO.write(combinedImage, "png", output);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = output.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static String generate(String barcodeText,int width,int height) {
        // 生成条形码
        Code128Writer barcodeWriter = new Code128Writer();
        BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, width, height);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            MatrixToImageWriter.writeToStream(bitMatrix, "png", byteArrayOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}
